package dao;

import entity.College;
import util.DBUtil;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

//学院信息数据库操作类的定义
public class CollegeDao {

    //1.定义删除方法
    public int delete(int id){
        String sql="delete from tb_college where id='"+id+"' " ;
        int  n = DBUtil.update(sql);
        return n;
    }

    //2.定义查询的方法
    public List<College> getAll(){
        List<College> list  = new ArrayList<>();
        //从数据库的tb_college表中查询所有记录
        //遍历每条记录，生成一个College对象
        //返回College对象数组
        try {
            String sql = "select * from tb_college";
            ResultSet rs = DBUtil.query(sql);
            while (rs.next()) {
                 College  obj  = new College(); //创建Colleg对象
                 obj.setId(rs.getInt("id")); //属性赋值
                 obj.setName(rs.getString("name"));
                 list.add(obj); //加入到数组中
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return list;
    }

    //3.增加
    public int  add(College  obj){
        String sql="insert into tb_college(name) values('"+obj.getName()+"')";
        int  n  = DBUtil.update(sql);
        return n;
    }

    //4.修改
    public int update(College  obj){
        String sql="update tb_college set name='"+obj.getName()+"'  where id ='"+obj.getId()+"' ";
        int  n  = DBUtil.update(sql);
        return n;
    }

    //5.根据id获得对象
    public  College  getById(int id){
        College  obj = null ;
        try {
            String sql = "select * from tb_college where id="+id;
            ResultSet rs = DBUtil.query(sql);
            if (rs.next()) {
                obj  =  new College();
                obj.setId(rs.getInt("id")); //属性赋值
                obj.setName(rs.getString("name"));
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return obj;
    }
}

